﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using COUP.Core;
using COUP.Core.Enums;
using COUP.Core.Native;
using COUP.Core.Networking;
using COUP.Core.Cryptography;

namespace COUP.Auth.Networking
{
    public static class PacketHandler
    {
        public static void Handle_Packet(ClientState Owner, Packet Data)
        {
            switch (Data.Type)
            {             
                case 1051:
                    AuthConnect(Owner, Data); break;
                default:
                    Program.Output("Received Unknown Packet: Length " + Data.Length + ", Type " + Data.Type);
                    break;
            }
        }

        internal static unsafe void AuthConnect(ClientState Owner, Packet Data)
        {
            string accountName = string.Empty;
            string password = string.Empty;
            string serverName = string.Empty;
            //Get Authorization Details
            accountName = Encoding.ASCII.GetString(Data.Buffer, 4, 16).TrimEnd('\0');
            password = Encoding.ASCII.GetString(Data.Buffer, 20, 16).TrimEnd('\0');
            serverName = Encoding.ASCII.GetString(Data.Buffer, 36, 16).TrimEnd('\0');        

            password = SHA2.sha256encrypt(PasswordCrypt.Decrypt(Encoding.ASCII.GetBytes(password)));

            //Database Lookups and Checks to confirm Auth success
            //Assume success for now

            LoginError Login = LoginError.None;                       

            switch (Login)
            {
                case LoginError.None:
                    {
                        Program.Output("Account: '" + accountName + "' Password: '" + password + "' Status: Authenticated");

                        int AccountID = (Program.Logins += 1);

                        AccountID ^= Owner.LoginToken;
                        AccountID ^= Owner.RemoteHash;

                        Owner.Send(new TokenPacket(AccountID, Owner.LoginToken, Settings.GameServerIP, 5817));
                        Owner.Disconnect();
                        break;
                    }
                case LoginError.Offline:
                    break;
                case LoginError.Password:
                    break;
                case LoginError.Server:
                    break;
                case LoginError.Username:
                    break;
                case LoginError.Banned:
                    break;
            }
        }
    }
}
